<?php

declare (strict_types = 1);

namespace app\common\service\file;

use app\common\exception\AdminException;
use app\common\repository\file\FileCateRepository;
use app\common\service\BaseService;

class FileCateService extends BaseService
{
    public function __construct(FileCateRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * 获取文件分类列表
     *
     * @param array $where
     * @return \think\Collection|array
     */
    public function getList(array $where = []): \think\Collection|array
    {
        $data = $this->repository->getByWhere($where)->toArray();
        return get_tree($data);
    }

    /**
     * 获取文件分类详情信息
     *
     * @param $id
     * @return \app\common\model\BaseModel|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInfo($id): ?\app\common\model\BaseModel
    {
        return $this->repository->getOne($id);
    }

    /**
     * 创建文件分类信息
     *
     * @param array $data
     * @return \app\common\model\BaseModel|array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function create(array $data): \app\common\model\BaseModel|array
    {
        return $this->repository->save($data);
    }

    /**
     * 更新文件分类信息
     *
     * @param array $data
     * @param $id
     * @return bool|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update(array $data, $id): bool|int
    {
        if(empty($id)) {
            throw new AdminException('ID 不能为空');
        }
        $data = [
            'pid' => $data['pid'],
            'cate_name' => $data['cate_name']
        ];
        return $this->repository->update($data, $id);
    }

    /**
     * 删除文件分类信息
     *
     * @param $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete($id): bool
    {
        return $this->repository->delete($id);
    }
}